package com.example.demo.delete;

import org.apache.log4j.Logger;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * sojson 免费获取天气（限制太多，一天获取一次，有时还可能有bug的情况）
 *
 * @version 1.0.0.0
 * @auhtor 崔少良 2018/6/4 0004
 */
public class Test {
    private static final Logger logger = Logger.getLogger(Test.class.getSimpleName());

    public static void main(String[] args) {
        try {
            json();
            System.out.println("-----------------------------------------------------------------------------");
            xml();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 天气预报 API 接口 JSON返回
     *
     * @author Create by 崔少良 2018-06-04 下午 5:49
     */
    public static void json() throws Exception {
        //参数url化
        String city = java.net.URLEncoder.encode("沈阳", "utf-8");

        //拼地址
        String apiUrl = String.format("https://www.sojson.com/open/api/weather/json.shtml?city=%s", city);
        URL realUrl = new URL(apiUrl);
        if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
            SslUtils.ignoreSsl();
        }
        //开始请求
        URL url = new URL(apiUrl);

        URLConnection open = url.openConnection();
        InputStream input = open.getInputStream();
        //这里转换为String，带上包名，怕你们引错包
        String result = org.apache.commons.io.IOUtils.toString(input, "utf-8");

        //输出
        System.out.println(result);
    }

    /**
     * 天气预报 API XML返回方式
     *
     * @author Create by 崔少良 2018-06-04 下午 5:49
     */
    public static void xml() throws Exception {
        //参数url化
        String city = java.net.URLEncoder.encode("沈阳", "utf-8");

        //拼地址
        String apiUrl = String.format("https://www.sojson.com/open/api/weather/xml.shtml?city=%s", city);
        URL realUrl = new URL(apiUrl);
        if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
            SslUtils.ignoreSsl();
        }
        //开始请求
        URL url = new URL(apiUrl);
        URLConnection open = url.openConnection();
        InputStream input = open.getInputStream();
        //这里转换为String，带上包名，怕你们引错包
        String result = org.apache.commons.io.IOUtils.toString(input, "utf-8");
        //输出
        System.out.println(result);
    }
}
